package crypto_util

import (
	"bytes"
	"crypto/aes"
	"crypto/cipher"
	"encoding/base64"
	"log"
)

var aesKey = []byte("7A75D8A3F6BF4F6B")

func pkcs7Padding(ciphertext []byte, blockSize int) []byte {
	padding := blockSize - len(ciphertext)%blockSize
	padtext := bytes.Repeat([]byte{byte(padding)}, padding)
	return append(ciphertext, padtext...)
}

func pkcs7UnPadding(origData []byte) []byte {
	length := len(origData)
	unpadding := int(origData[length-1])
	return origData[:(length - unpadding)]
}

func Encrypt(code string) string {
	block, err := aes.NewCipher(aesKey)
	if err != nil {
		log.Println(err)
		return code
	}
	blockSize := block.BlockSize()
	origData := pkcs7Padding([]byte(code), blockSize)
	blockMode := cipher.NewCBCEncrypter(block, aesKey[:blockSize])
	crypted := make([]byte, len(origData))
	blockMode.CryptBlocks(crypted, origData)
	return base64.StdEncoding.EncodeToString(crypted)
}

func Decrypt(code string) string {
	block, err := aes.NewCipher(aesKey)
	if err != nil {
		log.Println(err)
		return code
	}
	blockSize := block.BlockSize()
	blockMode := cipher.NewCBCDecrypter(block, aesKey[:blockSize])
	crypted, err := base64.StdEncoding.DecodeString(code)
	if err != nil {
		log.Fatal(err)
	}
	origData := make([]byte, len(crypted))
	blockMode.CryptBlocks(origData, crypted)
	origData = pkcs7UnPadding(origData)
	return string(origData)
}
